/**
 *    @file       process.cpp
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       02/11/2014 03:34:38 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com
 */
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include "process.h"

process::process()
	: m_ifparent(false), m_ifchild(false), m_iffork(false)
{

}

process::~process()
{

}

bf_int_t process::fork()
{
	if (m_iffork && m_ifchild)
	{
		return BF_ERROR;
	}
	bf_int_t ret = 0;
	bf_pid_t pid = fork();
	switch (pid)
	{
		case -1:
			{
				ret = BF_ERROR;
				break;
			}
		case 0:
			{
				m_iffork = true;
				m_ifchild = true;
				m_ifparent = false;
				ret = BF_OK;
				break;
			}
		default:
			{
				m_iffork = true;
				m_ifparent = true;
				ret = BF_OK;
				m_childpid.push_back(pid);
				break;
			}
	}
	return ret;
}

void process::waitpid()
{
	bf_int_t status;
	bf_int_t errno_tmp;
	bf_pid_t deadpid;
	errno_tmp = errno;
	while (true)
	{
		deadpid = waitpid(0, &status, WNOHANG);
		if (deadpid > 0) continue;
	}
	errno = errno_tmp;
}

//static///////////////
bf_pid_t process::m_pid = 0;
bf_pid_t process::getpid()
{
	if (m_pid == 0)
	{
		m_pid = ::getpid();
	}
	return m_pid;
}

bf_pid_t process::getppid()
{
	return ::getppid();
}

bf_pid_t process::waitpid(bf_pid_t pid, bf_int_t *status, bf_int_t options)
{
	return ::waitpid(pid, status, options);
}

